<script setup lang="ts">
import { UserFilled, Edit, Plus } from '@element-plus/icons-vue';
import UserRoleSelect from '../UserRoleSelect.vue';
import { IPromoterNodeConfig, EUserSelectType } from '../types';
import { useNodeConfig, useOpenSelect } from '../hooks';
import AddNode from './AddNode.vue';

const { selectRef, openSelect } = useOpenSelect();

const model = defineModel<IPromoterNodeConfig>({ default: {} });

const { drawerVisible, isEditTitle, form, nodeConfig, nodeTitleRef, show, editTitle, save } = useNodeConfig(model);

function toText(nodeConfig: IPromoterNodeConfig) {
	if (nodeConfig.nodeRoleList && nodeConfig.nodeRoleList.length > 0) {
		return nodeConfig.nodeRoleList.map((item) => item.name).join('、');
	} else {
		return '所有人';
	}
}

function delRole(index: number) {
	form.value.nodeRoleList.splice(index, 1);
}
</script>

<template>
	<div class="node-wrap">
		<div class="node-wrap-box start-node" @click="show">
			<div class="title" style="background: #576a95">
				<el-icon class="icon">
					<UserFilled />
				</el-icon>
				<span>{{ nodeConfig.nodeName }}</span>
			</div>
			<div class="content">
				<span>{{ toText(nodeConfig) }}</span>
			</div>
		</div>

		<add-node v-model="nodeConfig.childNode"></add-node>

		<el-drawer title="发起人" v-model="drawerVisible" destroy-on-close append-to-body :size="500">
			<template #header>
				<div class="node-wrap-drawer__title">
					<label @click="editTitle" v-if="!isEditTitle"
						>{{ form.nodeName
						}}<el-icon class="node-wrap-drawer__title-edit">
							<Edit /> </el-icon
					></label>
					<el-input
						v-if="isEditTitle"
						ref="nodeTitleRef"
						v-model="form.nodeName"
						clearable
						@blur="isEditTitle = false"
						@keyup.enter="isEditTitle = false"
					></el-input>
				</div>
			</template>
			<el-container>
				<el-main style="padding: 0 20px 20px 20px">
					<el-form label-position="top">
						<el-form-item label="谁可以发起此审批">
							<el-button type="primary" :icon="Plus" round @click="openSelect(EUserSelectType.ROLE)">选择角色</el-button>
							<div class="tags-list">
								<el-tag v-for="(role, index) in form.nodeRoleList" :key="role.id" type="info" closable @close="delRole(index)">{{
									role.name
								}}</el-tag>
							</div>
						</el-form-item>
						<el-alert v-if="form.nodeRoleList.length == 0" title="不指定则默认所有人都可发起此审批" type="info" :closable="false" />
					</el-form>
				</el-main>
				<el-footer>
					<el-button type="primary" @click="save">保存</el-button>
					<el-button @click="drawerVisible = false">取消</el-button>
				</el-footer>
			</el-container>

			<UserRoleSelect ref="selectRef" v-model="form.nodeRoleList" />
		</el-drawer>
	</div>
</template>
